#include "stdafx.h"
#include "CallStack.h"

CallStack::CallStack(RAM^ memory)
{
	this->CallStack::CallStack(memory, 0, DEFUALT_SIZE);
}

CallStack::CallStack(RAM^ memory, int baseOffset)
{
	this->CallStack::CallStack(memory, baseOffset, DEFUALT_SIZE);
}

CallStack::CallStack(RAM^ memory, int baseOffset, int size)
{
	this->size = size;
	growthSize = 127;
	this->baseOffset = baseOffset;
	this->memory = memory;
}

UInt32 CallStack::GetValueAt(UInt32 i)
{
	return memory[i + baseOffset];
}

void CallStack::SetValueAt(UInt32 i, UInt32 value)
{
	if (i >= size && i < size + growthSize)
	{
		Grow();
	}

	memory[i + baseOffset] = value;
}

void CallStack::Grow()
{
	size += growthSize;

	Console::WriteLine("Stack size increased. New size: ", size);
}

Boolean CallStack::LoadDataArray(array<UInt32>^ dataHandle, UInt32 startAddress)
{
	int freeSpace = size - startAddress;

	if (dataHandle->Length > freeSpace)
	{
		int growAmount = Math::Ceiling((double)(dataHandle->Length - freeSpace) / growthSize);

		for (int i = 0; i < growAmount; i++)
		{
			Grow();
		}
	}

	return memory->LoadIntoMemory(dataHandle, startAddress);
}
